package com.ruoyi.nongjt.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.nongjt.domain.Certificate;
import com.ruoyi.nongjt.mapper.CertificateMapper;
import com.ruoyi.nongjt.service.ICertificateService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 合格证管理Service实现
 *
 * @author ruoyi
 * @date 2024-04-05
 */
@Service
public class CertificateServiceImpl implements ICertificateService
{
    @Autowired
    private CertificateMapper certificateMapper;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 根据合格证ID查询合格证
     */
    @Override
    public Certificate selectCertificateByCertificateId(Long certificateId)
    {
        Certificate certificate = new Certificate();
        certificate.setCertificateId(certificateId);
        List<Certificate> certificates = certificateMapper.selectCertificateList(certificate);
        return certificates != null && !certificates.isEmpty() ? certificates.get(0) : null;
    }

    /** 文件上传路径 */
    private static final String UPLOAD_PATH = "/home/ruoyi/upload/report/";

    /**
     * 批量生成合格证编号
     */
    @Override
    public List<String> batchGenerateCodes(Integer count, Certificate certificate)
    {
        List<String> certificateCodes = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String prefix = "NJ" + dateStr;

        // 生成指定数量的合格证编号
        for (int i = 0; i < count; i++) {
            // 生成唯一编号，格式：NJ+年月日+6位随机数
            String randomCode = generateRandomCode(6);
            String code = prefix + randomCode;
            certificateCodes.add(code);

            // 保存临时生成的合格证信息
            Certificate tempCert = new Certificate();
            tempCert.setCode(code);
            tempCert.setProductName(certificate.getProductName());
            tempCert.setWeight(certificate.getWeight());
            tempCert.setQuantity(certificate.getQuantity());
            tempCert.setSourceType(certificate.getSourceType());
            tempCert.setTestingOrg(certificate.getTestingOrg());
            tempCert.setStatus("temp");
            tempCert.setCreateTime(new Date());
            tempCert.setCreateBy(SecurityUtils.getUsername());

            certificateMapper.insertCertificate(tempCert);
        }

        return certificateCodes;
    }

    /**
     * 确认打印合格证
     */
    @Override
    public void confirmPrint(List<String> certificateCodes, List<String> reportUrls)
    {
        for (String code : certificateCodes) {
            Certificate certificate = certificateMapper.selectCertificateByCode(code);
            if (certificate != null && "temp".equals(certificate.getStatus())) {
                certificate.setStatus("printed");
                certificate.setPrintTime(new Date());
                certificate.setReportUrls(reportUrls);
                certificateMapper.updateCertificate(certificate);
            }
        }
    }

    /**
     * 取消临时合格证记录
     */
    @Override
    public void cancelTempCertificates(List<String> certificateCodes)
    {
        certificateMapper.deleteCertificateByCodes(certificateCodes);
    }

    /**
     * 通过编号查询合格证
     */
    @Override
    public Certificate selectCertificateByCode(String code)
    {
        return certificateMapper.selectCertificateByCode(code);
    }

    /**
     * 查询合格证列表
     */
    @Override
    public List<Certificate> selectCertificateList(Certificate certificate)
    {
        // 设置当前用户只能查看自己生成的合格证
        certificate.setCreateBy(SecurityUtils.getUsername());
        return certificateMapper.selectCertificateList(certificate);
    }

    /**
     * 溯源查询合格证
     */
    @Override
    public Certificate traceCertificate(String code)
    {
        Certificate certificate = certificateMapper.selectCertificateByCode(code);
        if (certificate != null) {
            // 如果是管理员或生成人，可以查看所有信息
            String currentUser = SecurityUtils.getUsername();
            if (SecurityUtils.isAdmin(SecurityUtils.getUserId()) || currentUser.equals(certificate.getCreateBy())) {
                return certificate;
            } else {
                // 非管理员和生成人，只返回公开信息
                Certificate publicCert = new Certificate();
                publicCert.setCode(certificate.getCode());
                publicCert.setProductName(certificate.getProductName());
                publicCert.setWeight(certificate.getWeight());
                publicCert.setQuantity(certificate.getQuantity());
                publicCert.setSourceType(certificate.getSourceType());
                publicCert.setTestingOrg(certificate.getTestingOrg());
                publicCert.setStatus(certificate.getStatus());
                publicCert.setCreateTime(certificate.getCreateTime());
                publicCert.setPrintTime(certificate.getPrintTime());
                publicCert.setVoidTime(certificate.getVoidTime());
                return publicCert;
            }
        }
        return null;
    }

    /**
     * 获取当前用户的合格证统计数据
     */
    @Override
    public Object getMyCertificateStats(Long userId, String startDate, String endDate)
    {
        Map<String, Object> stats = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);

        // 查询统计数据
        Integer totalCount = certificateMapper.selectTotalCountByUser(params);
        Integer printedCount = certificateMapper.selectCountByStatusAndUser("printed", params);
        Integer voidCount = certificateMapper.selectCountByStatusAndUser("void", params);

        stats.put("totalCount", totalCount);
        stats.put("printedCount", printedCount);
        stats.put("voidCount", voidCount);

        // 获取最近生成的合格证
        params.put("limit", 5);
        List<Certificate> recentCertificates = certificateMapper.selectRecentCertificatesByUser(params);
        stats.put("recentCertificates", recentCertificates);

        return stats;
    }

    /**
     * 上传检测报告文件
     */
    @Override
    public String uploadReportFile(MultipartFile file)
    {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        // 创建目录
        File uploadDir = new File(UPLOAD_PATH);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        try {
            // 保存文件
            file.transferTo(new File(UPLOAD_PATH + fileName));
            // 返回文件访问URL
            return "/report/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 作废合格证
     */
    @Override
    public void voidCertificate(String code, String reason)
    {
        Certificate certificate = certificateMapper.selectCertificateByCode(code);
        if (certificate != null && "printed".equals(certificate.getStatus())) {
            certificate.setStatus("void");
            certificate.setVoidTime(new Date());
            certificate.setVoidReason(reason);
            certificateMapper.updateCertificate(certificate);
        } else {
            throw new RuntimeException("该合格证无法作废");
        }
    }

    /**
     * 生成随机码
     */
    private String generateRandomCode(int length)
    {
        String chars = "0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 新增合格证
     */
    @Override
    public int insertCertificate(Certificate certificate)
    {
        certificate.setCreateTime(DateUtils.getNowDate());
        certificate.setCreateBy(SecurityUtils.getUsername());
        return certificateMapper.insertCertificate(certificate);
    }

    /**
     * 修改合格证
     */
    @Override
    public int updateCertificate(Certificate certificate)
    {
        certificate.setUpdateTime(DateUtils.getNowDate());
        certificate.setUpdateBy(SecurityUtils.getUsername());
        return certificateMapper.updateCertificate(certificate);
    }

    /**
     * 批量删除合格证
     */
    @Override
    public int deleteCertificateByCertificateIds(Long[] certificateIds)
    {
        // 将Long数组转换为String列表
        List<String> codeList = new ArrayList<>();
        if (certificateIds != null && certificateIds.length > 0)
        {
            for (Long id : certificateIds)
            {
                Certificate certificate = selectCertificateByCertificateId(id);
                if (certificate != null)
                {
                    codeList.add(certificate.getCode());
                }
            }
        }
        // 使用现有的deleteCertificateByCodes方法
        return certificateMapper.deleteCertificateByCodes(codeList);
    }
}